package com.kevin.mybatis.configuration.datascope.handler;

import com.kevin.mybatis.configuration.datascope.util.DataScopeUtil;
import com.kevin.mybatis.model.DataScope;
import com.kevin.mybatis.model.LoginUser;
import com.kevin.mybatis.service.UserService;
import jakarta.annotation.Resource;
import net.sf.jsqlparser.expression.Expression;

import java.util.List;

public class DataPermissionHandler extends DataScopeHandler {

    @Resource
    private UserService userService;

    // 根据组织机构拦截数据
    private static final String SCOPE_FIELD = "org_id";
    // 根据操作用户拦截数据
    private static final String USER_FIELD = "create_by";

    @Override
    public Expression setExpression(Expression where, String tableName) {
        // 获取当前登录用户信息
        LoginUser user = userService.getLoginUser();
        if (null != user) {
            DataScope dataScope = DataScope.valueOfId(user.getDatascope());
            return switch (dataScope) {
                case ALL -> DataScopeUtil.all(where);
                case CUS, CURRENT_SUB ->
                        DataScopeUtil.inExpression(where, tableName, SCOPE_FIELD, List.of(user.getRangeList()));
                case CURRENT ->
                        DataScopeUtil.equalsExpression(where, tableName, SCOPE_FIELD, List.of(user.getRangeList()));
                case MYSELF ->
                        DataScopeUtil.equalsExpression(where, tableName, USER_FIELD, List.of(user.getRangeList()));
            };
        }
        // 获取不到用户信息，无权查看任何数据
        return DataScopeUtil.noData(where);
    }

}
